﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Web.Mvc;
using QD.Framework.DAL;
using QD.Framework.File;
using QD.Web.Management.Infrastructure;
using QD.Web.Management.Infrastructure.Razor;
using QD.Models.@(Model.ControllerName);


namespace QD.Web.Management.Controllers
{
    public class @(Model.ControllerName)Controller : BaseController
    {
        private readonly IRepository<@(Model.TableName)> _@(Model.TableName)Repository;
        private readonly IExcelClient _excelClient;
        public  @(Model.ControllerName)Controller(IRepository<@(Model.TableName)> @(Model.TableName)Repository,
            IExcelClient excelClient)
        {
            _@(Model.TableName)Repository = @(Model.TableName)Repository;			
            this._excelClient = excelClient;
        }

        [Permission(PermCode.XXX)]
        public ActionResult Index(Query<Models.@(Model.ControllerName).@(Model.DomainModelName), @(Model.ParamName)> query)
        {
            var where = GetExpression(query);
            _@(Model.TableName)Repository.PageList(where, o => o.Desc(m => m.CreateTime), query.__pageIndex, query.__pageSize)
                 .MapTo<@(Model.TableName), Models.@(Model.ControllerName).@(Model.DomainModelName)>()
                .UpdateQuery(query);            
            return PageView(query);
        }


        public Expression<Func<@(Model.TableName), bool>> GetExpression(Query<Models.@(Model.ControllerName).@(Model.DomainModelName),  @(Model.ParamName)> query)
        {
            var where = PredicateBuilder.True<@(Model.TableName)>();
            var args = query.Params;
            return where;
        }
        [Permission(PermCode.XXX)]
		public void Export(Query<@(Model.TableName), @(Model.ParamName)> query)
        {
            var where = GetExpression(query);
            var list =  _@(Model.TableName)Repository.ToList(where, o => o.Desc(m => m.CreateTime));
            var exportList = new List<@(Model.ExportModel)>();

            foreach (var item in list)
            {
                exportList.Add(new @(Model.ExportModel)()
                {
                    @foreach (var temp in Model.Columns)
                    {
						@:@(temp.name) = item.@(temp.name).ToString() ,
                    }
                });
            }

            _excelClient.HttpExport(exportList, "XXX" + DateTime.Now.ToString("yyyyMMddHHmmss"));
        }
    }
}